
const data = []
let id = 0

/**
 * 列表读取
 * @param {*} params 
 */
export function getList(params) {
  // 取参数声明并设置默认值
  const { pageSize = 10, pageNum = 1 } = params
  const offset = (pageNum - 1) * pageSize
  const limit = pageSize

  // 取出分页数据
  return Promise.resolve({
    code: 0,
    data: {
      total: data.length,
      list: data.slice(offset, offset + limit),
      pageSize,
      pageNum
    }
  })
}

/**
 * 添加
 * @param {*} params 
 */
export function add(params) {
  id++
  const item = {
    ...params,
    id
  }
  data.push(item)
  return Promise.resolve({
    code: 0,
    data: item
  })
}

/**
 * 更新
 * @param {*} params 
 */
export function update(params) {
  const index = data.findIndex((item) => params.id === item.id)
  if (index !== null) {
    // 保留原参数，只修改入参部分
    data[index] = {
      ...data[index],
      ...params
    }
  }

  return Promise.resolve({
    code: 0,
    data: data[index]
  })
}

/**
 * 删除
 * @param {*} params 
 */
export function remove(params) {
  const index = data.findIndex((item) => params.id === item.id)
  if (index !== null) {
    // 删除数组
    data.splice(index, 1)
  }

  return Promise.resolve({
    code: 0
  })
}
